<%@ Page Language="C#" Inherits="IBuyAdventure.PageBase" src="components/stdpage.cs" clienttarget=downlevel %>
<%@ Register TagPrefix="IBA" TagName="Header" Src="UserControl\Header.ascx" %>
<%@ Register TagPrefix="IBA" TagName="Footer" Src="UserControl\Footer.ascx" %>
<%@ Register TagPrefix="IBA" TagName="Categories" Src="UserControl\Categories.ascx" %>
<%@ Import Namespace="System.Data" %>

<HTML>
  <HEAD>
    <TITLE>IBuyAdventure Catalog</TITLE>
  </HEAD>
 
  <script language="C#" runat="server" >

      // Total for shopping basket

      double fTotal = 0;

      void Page_Load(Object sender, EventArgs e) {
                
           IBuyAdventure.CartDB cart = new IBuyAdventure.CartDB(getConnStr());  
                
           // If a new product to add is specified, add it to the shopping cart      
                     
           if (Request.Params["ProductCode"] != null) {
              cart.AddShoppingCartItem(GetCustomerID(),Request.Params["ProductCode"]);
           }           
                     
           // If page is not being loaded in response to postback
          
           if (Page.IsPostBack == false) { 
              PopulateShoppingCartList();        
              UpdateSelectedItemStatus();
           }    
 
        
           
 
      }
         
      void UpdateSelectedItemStatus() {
           if  ( MyList.Items != null ) {
              status.Text = "You have selected " + MyList.Items.Count +" items " + "so far:<br>";   
              }
           else {
              status.Text = "You have selected no items so far";
              }
      }
 
      void Recalculate_Click(Object sender, EventArgs e) {
      
        // Update Shopping Cart
        
        UpdateShoppingCartDatabase();
        
        // Repopulate ShoppingCart List
        
        PopulateShoppingCartList();

        UpdateSelectedItemStatus();
        
      }
      
      void Checkout_Click(Object sender, EventArgs e) {
        
        // Update Shopping Cart
        
        UpdateShoppingCartDatabase();
        Response.Redirect("secure/Checkout.aspx");
      }

      String GetCustomerID() {
       
        if (User.Identity.Name != "") {
          return Context.User.Identity.Name;
        }
        else {
	   if (Session["AnonUID"] == null)
		Session["AnonUID"] = Guid.NewGuid();
	   return Session["AnonUID"].ToString();
        }
      }
      
      void UpdateShoppingCartDatabase() {
      
        IBuyAdventure.ProductsDB inventory = new IBuyAdventure.ProductsDB(getConnStr());  
        IBuyAdventure.CartDB cart = new IBuyAdventure.CartDB(getConnStr());  

      
        // Iterate through all rows within shopping cart list
      
        for (int i=0; i<MyList.Items.Count; i++) {
        

          // Obtain references to row's controls
        
          TextBox quantityTxt = (TextBox) MyList.Items[i].FindControl("Quantity");
          CheckBox remove = (CheckBox) MyList.Items[i].FindControl("Remove");
          HtmlInputHidden shoppingCartIDTxt = (HtmlInputHidden) MyList.Items[i].FindControl("ShoppingCartID");

                  
          // If removed checkbox selected, delete the item.  Otherwise, update its
          // quantity (todo: a product quality app should only update if value was been changed)
             
          // Convert quantity to a number

          int Quantity = Int32.Parse(quantityTxt.Text);

          if (remove.Checked == true || Quantity  == 0) {
            cart.DeleteShoppingCartItem(Int32.Parse(shoppingCartIDTxt.Value));
            }
          else
            cart.UpdateShoppingCartItem(Int32.Parse(shoppingCartIDTxt.Value), Quantity );
        }


      }
      
      void PopulateShoppingCartList() {
      
        // Popoulate list with updated shopping cart data
        
        IBuyAdventure.CartDB cart = new IBuyAdventure.CartDB(getConnStr());  
        
        DataSet ds = cart.GetShoppingCartItems(GetCustomerID());

        MyList.DataSource = ds;
        MyList.DataBind();   

        // Walk through table and calculate the total value 

        DataTable dt;
        dt = ds.Tables[0];

        int lIndex;
        double UnitPrice;
        int Quantity;

        for ( lIndex =0; lIndex < dt.Rows.Count; lIndex++ ) { 

           UnitPrice = (double) dt.Rows[lIndex]["UnitPrice"];
         
           Quantity = (int) dt.Rows[lIndex]["Quantity"];

           if ( Quantity > 0 ) {
              fTotal += UnitPrice * Quantity;
            }
         }
        
      }
      

  </script>

  <BODY BACKGROUND="images/back_sub.gif"> 

    <form runat="server">

      <FONT FACE="Verdana, Arial, Helvetica" SIZE=2>

        <TABLE BORDER=0 VALIGN=TOP width=100% style="font: 10pt verdana">
          
          <tr>
            <td colspan=5>        
              <IBA:Header id="Header" runat="server"/>
            </td>
          </tr>
          
          <!--Begin Navigational Buttons-->

          <TR VALIGN=TOP>
            <TD width=95 ALIGN=LEFT VALIGN=TOP>

              <IBA:Categories id="Categories" runat="server"/>
              
              
            </TD>
            <td>
              &nbsp;&nbsp;
            </td>
            <TD valign=top align=left>
            
              <img src="images/hd_Check_out.gif">
              
              <br><br>

              <font size=2><asp:label id="status" runat="server" /></font><br>

              <Table COLSPAN=8 CELLPADDING=5 BORDER=0 valign=top>

                <!-- BEGIN column header row -->

                <TR valign=top>  
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Remove</FONT>
                  </TD>                              
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Product Code</FONT>
                  </TD>
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Product Name</FONT>
                  </TD>
                  <TD ALIGN=CENTER WIDTH=250 BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Description</FONT>
                  </TD>
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Quantity</FONT>
                  </TD>
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Unit Price</FONT>
                  </TD>
                  <TD ALIGN=CENTER BGCOLOR="#800000">
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="#ffffff" SIZE=2>Unit Total</FONT>
                  </TD>                
                </TR>

                <asp:repeater id="MyList"  runat="server">
                
                  <itemtemplate>
                    <TR>           
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <asp:checkbox id="Remove" runat="server"/>
                        </FONT>
                      </TD>                    
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <input id="ShoppingCartID" type=hidden value='<%#DataBinder.Eval(Container.DataItem, "ShoppingCartID", "{0:g}") %>' runat="server">
 
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <%#DataBinder.Eval(Container.DataItem, "ProductCode")%>
                        </FONT>
                      </TD>
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <%#DataBinder.Eval(Container.DataItem, "ProductName")%>
                        </FONT>
                      </TD>
                      <TD ALIGN=LEFT WIDTH=250 BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <%#DataBinder.Eval(Container.DataItem, "Description")%>
                        </FONT>
                      </TD>
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <asp:textbox id="Quantity" text=<%#DataBinder.Eval(Container.DataItem, "Quantity", "{0:g}")%> width=30 runat="server"/>
                        </FONT>
                      </TD>
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <asp:label id="UnitPrice" runat="server"><%#DataBinder.Eval(Container.DataItem, "UnitPrice", "{0:C}")%></asp:label>
                        </FONT>
                      </TD>
                      <TD ALIGN=CENTER BGCOLOR="#f7efde">
                        <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                          <%# String.Format("{0:C}", ( ((int)DataBinder.Eval(Container.DataItem, "Quantity")) * ((double) DataBinder.Eval(Container.DataItem, "UnitPrice")) )) %>
                        </FONT>
                      </TD>
                    </TR>
                  </itemtemplate>
                  
                </asp:repeater>
                <TR>
                  <TD colspan=5><TD colspan=3 align=right>
                    <FONT STYLE="Verdana, Arial, Helvetica" COLOR="black" SIZE=2>
                      Total is <%=String.Format("{0:C}", fTotal ) %>
                    </FONT>
                  </TD>
                </TR>
                <TR>
                  <TD colspan=8 align=right>
                    <asp:button text="Recalculate" OnClick="Recalculate_Click" runat="server"/>
                    <asp:button text="Go To Checkout" OnClick="Checkout_Click" runat="server"/>
                  </TD>
                </TR>
             
              </table>
             <IBA:footer runat="server"/></TD> </TR>
            </TD>
          </TR>
        </TABLE>
      </FONT>
    </form>

  </BODY>
</HTML>
